package com.tsing.cli.system.filter;

import cn.hutool.jwt.JWTUtil;
import com.tsing.cli.common.config.RedisManager;
import com.tsing.cli.common.dto.CustomUserDetails;
import com.tsing.cli.system.constant.AuthConstants;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * token过滤器
 *
 * @author TheTsing
 */
@RequiredArgsConstructor
public class TokenFilter extends OncePerRequestFilter {

    private final Long tokenExpire;

    private final RedisManager redisManager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(AuthConstants.AUTHENTICATION_HEAD);
        if (Objects.nonNull(token) && token.startsWith(AuthConstants.TOKEN_PREFIX)) {
            token = token.substring(AuthConstants.TOKEN_PREFIX.length());
            try {
                String id = JWTUtil.parseToken(token).getPayload("id").toString();
                String key = AuthConstants.REDIS_TOKEN_PREFIX + id + "_" + token;
                if (redisManager.getAndExpireString(key, tokenExpire, TimeUnit.SECONDS) instanceof CustomUserDetails customUserDetails) {
                    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(customUserDetails, null, customUserDetails.getAuthorities()));
                }
            } catch (Exception e) {
            }
        }
        filterChain.doFilter(request, response);
    }

}
